﻿using System;
using System.Collections.ObjectModel;
using VisualWip.Core;
using VisualWip.Core.Interfaces;

namespace VisualWip.TFS2010Providers
{
    public abstract class WorkItemQueryBase : IQuery
    {
        public Guid QueryId { get; set; }

        public bool DownloadDisplayFieldsOnly { get; set; }

        #region IQuery Members

        public PersistenceTree Persist(string name)
        {
            var settings = new PersistenceTree(name, this);
            settings.Add(() => QueryId);
            settings.Add(() => DownloadDisplayFieldsOnly);
            return settings;
        }

        public void Load(PersistenceTree settings)
        {
            QueryId = settings.Get(() => QueryId, Guid.Empty);
            DownloadDisplayFieldsOnly = settings.Get(() => DownloadDisplayFieldsOnly, false);
        }

        public string QueryText { get; set; }

        #endregion

        public Collection<WorkItem> GetWork(TfsWorkItemWorkProvider workItemWorkProvider)
        {
            RefreshQueryTextIfEmpty(workItemWorkProvider);
            try
            {
                return RunGetWork(workItemWorkProvider);
            }
            catch (Exception exception)
            {
                return new Collection<WorkItem>
                           {
                               new ErrorWorkItem(exception)
                           };
            }
        }

        protected abstract Collection<WorkItem> RunGetWork(TfsWorkItemWorkProvider workItemWorkProvider);

        public int GetWorkCount(TfsWorkItemWorkProvider workItemWorkProvider)
        {
            RefreshQueryTextIfEmpty(workItemWorkProvider);
            try
            {
                return RunGetWorkCount(workItemWorkProvider);
            }
            catch
            {
                return 0;
            }
        }

        protected abstract int RunGetWorkCount(TfsWorkItemWorkProvider workItemWorkProvider);

        private void RefreshQueryTextIfEmpty(TfsWorkItemWorkProvider workItemWorkProvider)
        {
            if (string.IsNullOrWhiteSpace(QueryText))
                QueryText = workItemWorkProvider.WorkItemStore.GetQueryDefinition(QueryId).QueryText;
        }
    }
}